package com.alibaba.springbootrbac.config;

import com.alibaba.springbootrbac.mapper.PermissionMapper;
import com.alibaba.springbootrbac.model.entity.Permission;
import com.alibaba.springbootrbac.model.enum1.PermissionEnum;
import jakarta.annotation.Resource;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author ZhouYaDong
 * @date 2025/8/24
 * @description
 */
@Component
public class PermissionInitializer implements CommandLineRunner {

    @Resource
    private PermissionMapper permissionMapper;

    @Override
    @Transactional
    public void run(String... args) throws Exception {
        System.out.println("开始同步 PermissionEnum 到数据库 permissions 表...");

        List<PermissionEnum> enumList = List.of(PermissionEnum.values());
        for (PermissionEnum pEnum : enumList) {

            // 查询数据库中是否已有该权限
            Permission dbPermission = permissionMapper.selectOne(
                    new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<Permission>()
                            .eq("name", pEnum.getCode())
            );

            if (dbPermission == null) {
                // 数据库不存在，插入
                Permission newPermission = new Permission();
                newPermission.setName(pEnum.getCode());
                newPermission.setDescription(pEnum.getDescription());
                newPermission.setModule(pEnum.getModule());
                newPermission.setModuleDesc(pEnum.getModuleDesc());
                newPermission.setCreateTime(LocalDateTime.now());
                newPermission.setUpdateTime(LocalDateTime.now());
                permissionMapper.insert(newPermission);
                System.out.println("插入权限: " + pEnum.getCode());
            } else {
                // 数据库已存在，更新信息（可选，防止覆盖 ID）
                dbPermission.setDescription(pEnum.getDescription());
                dbPermission.setModule(pEnum.getModule());
                dbPermission.setModuleDesc(pEnum.getModuleDesc());
                dbPermission.setUpdateTime(LocalDateTime.now());
                permissionMapper.updateById(dbPermission);
                System.out.println("更新权限: " + pEnum.getCode());
            }
        }

        System.out.println("PermissionEnum 同步完成！");
    }

}
